package org.ne.banksys.exception;


//import org.ne.springboot.pojo.Result;
import org.ne.banksys.common.Result;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wey
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Result handleException(Exception e) {
        e.printStackTrace();
        return Result.error(!e.getMessage().isEmpty() ? e.getMessage() : "操作失败！");
    }



    // 专精处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    // 固定返回400状态码
    public Result handleValidationException(MethodArgumentNotValidException ex) {
        // 提取所有字段错误
        List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
        // 构建结构化错误信息 {字段名: 错误描述}
        Map<String, String> errors = new HashMap<>();
        for (FieldError error : fieldErrors) {
            errors.put(error.getField(), error.getDefaultMessage());
        }
        errors.put("msg", "参数校验失败");
        return Result.error(errors);
        // 返回统一错误格式
    }
}
